Page({
  data: {
    planName: '',
    planType: 'collection', // collection: 绘本集计划, custom: 自定义计划
    dailyCount: 1,
    reviewSchedule: 'none', // none, 1, 2, 3, 4, 5
    selectedCollections: [],
    reviewOptions: [
      { value: 'none', label: '不复习' },
      { value: '1', label: '1次（第2天）' },
      { value: '2', label: '2次（第2, 5天）' },
      { value: '3', label: '3次（第2, 5, 8天）' },
      { value: '4', label: '4次（第2, 5, 8, 16天）' },
      { value: '5', label: '5次（第2, 5, 8, 16, 31天）' }
    ],
    showReviewPicker: false,
    estimatedDailyCount: 1
  },

  onLoad: function(options) {
    // 页面加载时的初始化
  },

  // 输入计划名称
  onPlanNameInput: function(e) {
    let value = e.detail.value.trim();
    if (value.length > 20) {
      value = value.substring(0, 20);
    }
    this.setData({
      planName: value
    });
  },

  // 切换计划类型
  onPlanTypeChange: function(e) {
    this.setData({
      planType: e.detail.value
    });
  },

  // 减少每天学习数量
  onDecreaseDailyCount: function() {
    if (this.data.dailyCount > 1) {
      this.setData({
        dailyCount: this.data.dailyCount - 1
      });
      this.calculateEstimatedDailyCount();
    }
  },

  // 增加每天学习数量
  onIncreaseDailyCount: function() {
    const maxCount = this.getMaxDailyCount();
    if (this.data.dailyCount < maxCount) {
      this.setData({
        dailyCount: this.data.dailyCount + 1
      });
      this.calculateEstimatedDailyCount();
    }
  },

  // 获取最大每天学习数量
  getMaxDailyCount: function() {
    // 根据选择的绘本集计算最大数量
    let totalBooks = 0;
    this.data.selectedCollections.forEach(collection => {
      totalBooks += collection.bookCount || 0;
    });
    return Math.max(1, totalBooks);
  },

  // 计算预估每天阅读数量
  calculateEstimatedDailyCount: function() {
    const newBooks = this.data.dailyCount;
    const reviewBooks = this.calculateReviewBooks();
    const total = newBooks + reviewBooks;
    
    this.setData({
      estimatedDailyCount: total
    });
  },

  // 计算复习书籍数量
  calculateReviewBooks: function() {
    const reviewSchedule = this.data.reviewSchedule;
    if (reviewSchedule === 'none') return 0;
    
    const reviewCount = parseInt(reviewSchedule);
    const totalBooks = this.data.selectedCollections.reduce((sum, collection) => {
      return sum + (collection.bookCount || 0);
    }, 0);
    
    // 简单估算：复习书籍约为新书籍的 reviewCount 倍
    return Math.min(reviewCount * this.data.dailyCount, totalBooks);
  },

  // 显示复习选择器
  showReviewPicker: function() {
    this.setData({
      showReviewPicker: true
    });
  },

  // 隐藏复习选择器
  hideReviewPicker: function() {
    this.setData({
      showReviewPicker: false
    });
  },

  // 选择复习策略
  onReviewScheduleChange: function(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      reviewSchedule: value,
      showReviewPicker: false
    });
    this.calculateEstimatedDailyCount();
  },

  // 添加绘本集
  onAddCollection: function() {
    wx.navigateTo({
      url: '/pages/collection-select/collection-select'
    });
  },

  // 移除绘本集
  onRemoveCollection: function(e) {
    const index = e.currentTarget.dataset.index;
    const collections = this.data.selectedCollections;
    collections.splice(index, 1);
    this.setData({
      selectedCollections: collections
    });
    this.calculateEstimatedDailyCount();
  },

  // 保存并预览
  onSaveAndPreview: function() {
    if (!this.validateForm()) {
      return;
    }

    const planData = {
      planName: this.data.planName,
      planType: this.data.planType,
      dailyCount: this.data.dailyCount,
      reviewSchedule: this.data.reviewSchedule,
      collectionIds: this.data.selectedCollections.map(item => item.id)
    };

    // 调用创建计划接口
    this.createReadingPlan(planData);
  },

  // 表单验证
  validateForm: function() {
    if (!this.data.planName.trim()) {
      wx.showToast({
        title: '请输入计划名称',
        icon: 'none'
      });
      return false;
    }

    if (this.data.selectedCollections.length === 0) {
      wx.showToast({
        title: '请选择绘本集',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 创建阅读计划
  createReadingPlan: function(planData) {
    wx.showLoading({
      title: '创建中...'
    });

    // 模拟API调用
    setTimeout(() => {
      wx.hideLoading();
      
      // 模拟成功响应
      const planId = 'plan_' + Date.now();
      
      wx.showToast({
        title: '创建成功',
        icon: 'success'
      });

      // 跳转到预览页面
      wx.navigateTo({
        url: `/pages/plan-preview/plan-preview?id=${planId}`
      });
    }, 1000);
  },

  // 返回上一页
  onBack: function() {
    wx.navigateBack();
  },

  // 阻止事件冒泡
  stopPropagation: function() {
    // 空函数，用于阻止事件冒泡
  },

  // 页面显示时更新数据
  onShow: function() {
    // 从全局数据获取选择的绘本集
    const app = getApp();
    if (app.globalData && app.globalData.selectedCollections) {
      this.setData({
        selectedCollections: app.globalData.selectedCollections
      });
      this.calculateEstimatedDailyCount();
    }
  }
}); 